package com.demo.dao;

import com.demo.entity.Users;
import com.demo.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UsersDAO {

    private SqlSession sqlSession;
    private List<Users> list;
    private Users user;

    private SqlSession getSession() {
        sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
        return sqlSession;
    }

    /**
     * 查找所有用户
     * @return
     */
    public List<Users> findAll () {
        try {
            list = getSession().selectList("findUsers");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return list;
    }

    /**
     * 查找指定 id 的用户
     * @param id
     * @return
     */
    public Users findById (Integer id) {
        try {
            user = getSession().selectOne("findUsers", new Users(id));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return user;
    }

    /**
     * 添加单个用户
     * @param user
     * @return
     */
    public Users addUser (Users user) {
        try {
            // 返回值：是insert执行过程中影响的行数
            getSession().insert("addUser", user);

            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return user;
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    public Users updateUsers (Users user) {
        try {
            getSession().update("updateUser", user);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return user;
    }

    public void delUser (Integer id) {
        try {
            getSession().delete("delUser", id);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

}
